const util = require('../../utils/util.js');
const api = require('../../config/api.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    auth:'',
    intervalId:'',
    intervalId2:'',
    flag:false
  },

  onLoad(options) {
    // console.log(JSON.stringify(options));
    
    // this.getAuthUrl();
    this.waitForAuthUrl();
    // 访问就发起请求
    this.getLoadAuthUrl();
    /*if (options.auth == 'undefined') {
      this.getAuthUrl();
      this.waitForAuthUrl();
    }else{
      this.setData({
        auth:decodeURIComponent(options.auth)
      })
      console.log('vvvv:'+this.data.auth)
    }*/
  },
  getLoadAuthUrl:function(){
    var that = this;
    var userid = wx.getStorageSync("userid");
    util.request(api.queryAuthUrlByUserid, {
      userid: userid
    }).then(function (res) {
      console.log('xxxxu::::'+JSON.stringify(res.data));
      if (res.data != null) {
        that.setData({
          auth: res.data,
          flag: true // 设置标志位
        });
        // clearInterval(that.data.intervalId2); // 获取到授权 URL 后清除定时器
      }else{
        that.getAuthUrl();
      }
    }).catch(err => {
      console.log(err)
    })
  },
  //数据库轮询获取认证链接
  getAuthUrl: function () {
    var that = this;
    var userid = wx.getStorageSync("userid");
    that.data.intervalId2 = setInterval(function () {
      util.request(api.queryAuthUrlByUserid, {
        userid: userid
      }).then(function (res) {
        console.log('xxxxu::::'+JSON.stringify(res.data));
        if (res.data != null) {
          that.setData({
            auth: res.data,
            flag: true // 设置标志位
          });
          clearInterval(that.data.intervalId2); // 获取到授权 URL 后清除定时器
        }
      }).catch(err => {
        console.log(err)
      })
    }, 6*1000);
  },
  waitForAuthUrl:function () {
    var that = this;
    if (that.data.flag) {
      clearInterval(that.data.intervalId);
      return;
    }
    that.data.intervalId = setTimeout(function () {
      that.waitForAuthUrl(); // 递归调用自身
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})